<template>
    <div id="ATable">
        <div class="ATable-btn">
            <el-row class="mb-4">
                <el-button type="primary" plain @click="blogadd">新增</el-button>
                <el-button type="primary" plain>
                    <label for="blog-input-file">导入</label>
                    <input
                            id="blog-input-file"
                            type="file"
                            class="file-btn"
                            multiple="multiplt"
                            accept=".xls,.xlsx"
                            @change="getFile($event)"
                            style="display: none"
                    >
                </el-button>
                <el-button type="primary" plain @click="downloadBlog">导出</el-button>
                <el-button type="primary" plain @click="downloadTemplate">导出模板</el-button>
                <el-input v-model="blogSearch" placeholder="请输入标题" clearable/>
                <el-button type="primary" plain @click="load">查询</el-button>
            </el-row>
        </div>
        <div class="ATable-content">
            <el-table
                    :data="tableData"
                    stripe
                    border
                    style="width: 100%"
                    :header-cell-style="headerCellStyle"
                    :cell-style="cellStyles"
            >
                <el-table-column prop="id" label="博客编号" width="150"/>
                <el-table-column prop="firstPicture" label="首图" width="150">
                    <template #default="scope">
                        <div class="demo-image__preview">
                            <el-image
                                    style="width: 100px; height: 100px"
                                    :src="scope.row.firstPicture"
                                    :preview-src-list="[scope.row.firstPicture]"
                                    :initial-index="1"
                            >
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="标题" width="150"/>
                <el-table-column prop="user.username" label="博主昵称" width="150"/>
                <!--        https://www.wangeditor.com/   富文本编辑框-->
                <el-table-column prop="content" label="内容" width="150">
                    <template #default="scope">
                        <el-button type="primary" plain @click="editBlogContent(scope.row)" style="width: 130px">
                            查看内容
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="views" label="浏览次数" width="150"/>
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" plain @click="blogEdit(scope.$index,scope.row)">编辑</el-button>
                        <el-button type="primary" plain @click="blogDelete(scope.$index,scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!--查询对话框        =============-->
            <el-dialog
                    v-model="dialogVisible2"
                    title="内容"
                    width="60vw"
            >
                <div class="dialog-content" v-html="curContent"></div>
                <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="confirmBlogContent" style="width:80px">确定</el-button>
          </span>
                </template>
            </el-dialog>
            <!--=========================-->
        </div>

        <div class="page">
            <div class="demo-pagination-block">
                <span class="demonstration"></span>
                <el-pagination
                        v-model:currentPage="currentPage"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                >
                </el-pagination>
            </div>
        </div>

        <el-dialog
                custom-class="blog-dialog-edit"
                v-model="dialogVisible"
                title="编辑"
                width="65vw"
                @opened="updateOpened"
                @closed="updateClosed()"
                @close="dialogClose"
        >
            <el-form :model="blogform" label-width="120px">
                <el-form-item label="首图">

                    <el-upload
                            ref="formRef"
                            class="blog-upload"
                            drag
                            :action="photoAction"
                            :headers="headers"
                            :on-success="fileUploadSuccess"
                            multiple
                    >
                        <el-icon class="el-icon--upload">
                            <UploadFilled/>
                        </el-icon>
                        <div class="el-upload__text">
                            拖拽文件 或者 <em>点击上传封面</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png 文件小于500kb
                            </div>
                        </template>
                    </el-upload>

                    <!--              <el-input v-model="blogform.firstPicture"></el-input>-->
                </el-form-item>
                <el-form-item label="标题">
                    <el-input v-model="blogform.title" style="width: 57vw"></el-input>
                </el-form-item>
                <!--        <el-form-item label="作者Id">-->
                <!--          <el-input v-model="blogform.userId"></el-input>-->
                <!--        </el-form-item>-->
                <el-form-item label="内容">
                    <!--          <el-input v-model="blogform.content"></el-input>-->
                    <div id="blogWangEdit" style="width: 57vw;height: 50vh"></div>
                </el-form-item>
                <!--        <el-form-item label="浏览次数">-->
                <!--          <el-input v-model="blogform.views"></el-input>-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="更新时间">-->
                <!--          <div class="demo-date-picker" style="margin-left: 20px">-->
                <!--            <div class="block">-->
                <!--              <el-date-picker v-model="blogform.updateTime" type="date" placeholder="选择日期">-->
                <!--              </el-date-picker>-->
                <!--            </div>-->
                <!--          </div>-->
                <!--        </el-form-item>-->
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="blogsave"
                >确认</el-button
                >
              </span>
            </template>
        </el-dialog>

    </div>
</template>

<script>
import request from "../../utils/request";
import {downloadBlog, uploadBlog} from "@/api/admin/blog";
import {UploadFilled} from '@element-plus/icons'
import E from 'wangeditor'
import {hex_md5} from '@/utils/md5'

export default {
    name: 'Blog',

    components: {
        UploadFilled
    },

    data() {
        return {
            tableData: [],
            currentPage: 1,
            total: 0,
            pageSize: 10,
            blogSearch: '',
            dialogVisible: false,
            blogform: {},
            dialogVisible2: '',
            tmpBlogContent: '',
            editor: null,
            curContent: '',
            photoAction: process.env.VUE_APP_BASE_API + "/files/upload",
            fileName: '',
            excelFile: null,
            addArr: []
        }
    },

    computed: {
        headers() {
            return {
                'token': sessionStorage.getItem("token")
            }
        }
    },

    created() {
        this.load(),
            this.dialogVisible2 = false
    },

    beforeDestroy() {
        this.beforeDestroy()
    },

    methods: {
        beforeDestroy() {
            // 销毁编辑器
            this.editor.txt.html('');
            this.editor.destroy();
            this.editor = null;
            this.description = ''
        },

        getFile(event) {
            console.log(event)
            this.excelFile = event.target.files
            this.fileName = this.excelFile[0].name

            for (let i = 0; i < this.excelFile.length; i++) {
                //    上传类型判断
                let imgName = this.excelFile[i].name
                let idx = imgName.lastIndexOf('.')
                if (idx == -1) {
                    console.debug("该文件不是正确的文件类型")
                    return
                }
                let xlxType = this.fileName.split('.')[1].toLowerCase() === 'xls'
                let xlsxType = this.fileName.split('.')[1].toLowerCase() === 'xlsx'
                if (!xlxType && !xlsxType) {
                    alert('上传模板只能是 xls、xlsx 格式!')
                }
                this.addArr.push(this.excelFile[i])
            }
            this.submitAddFile()
        },

        submitAddFile() {
            if (this.addArr.length === 0) {
                this.$message({
                    type: 'info',
                    message: '请选择要上传的文件'
                })
                return
            }
            const formData = new FormData()
            const extension = this.excelFile[0].name.split('.')[1]
            const fileName = this.excelFile[0].name.split('.')[0]
            formData.append('file', this.excelFile[0])
            formData.append('suffix', extension)
            formData.append('key', hex_md5(fileName + this.excelFile.size + extension))
            // formData.append('use', 'T')
            formData.append('name', fileName)
            formData.append('size', this.excelFile[0].size)
            formData.append('fileType', "blog")
            this.loading = true
            uploadBlog(formData)
                .then(() => {
                    this.addArr = []
                    this.excelFile = null
                    this.fileName = '未选择文件'
                    this.load()
                })
        },

        headerCellStyle({row, column, rowIndex, columnIndex}) {
            let styleJson = {
                "textAlign": "center",
            }
            return styleJson
        },

        cellStyles({row, column, rowIndex, columnIndex}) {
            let styleJson = {
                "textAlign": "center",
            }
            return styleJson
        },

        downloadBlog() {
            const action = process.env.VUE_APP_BASE_API + `/excel/downloadBlog?fileType=blog` //完整的接口地址
            window.open(action, '_self'); // _self参数设置是为了不跳转到新界面上去
        },
        downloadTemplate() {
            const action = process.env.VUE_APP_BASE_API + `/excel/downloadTemplate?fileType=blog` //完整的接口地址
            window.open(action, '_self'); // _self参数设置是为了不跳转到新界面上去
        },

        dialogClose() {
        },

        editBlogContent(row) {
            this.curContent = row.content;
            this.dialogVisible2 = true
        },
        //
        // contentOpened(){
        //   if( !this.editor || this.editor == null || this.editor == undefined ){
        //     const editor = new E("#blogWangEdit");
        //     this.editor = editor; // 保存创建的实例
        //   }
        //   console.log("this.editor",this.editor)
        //   // console.log("this.curContent",this.curContent)
        //   this.editor.create()
        //   this.editor.txt.html(this.curContent)
        //   console.log("this.editor.txt.html",this.editor.txt.html())
        //   console.log("this.curContent",this.curContent)
        // },

        // contentClosed(){
        //   this.beforeDestroy()
        // },
        updateClosed() {
            this.beforeDestroy()
        },

        confirmBlogContent() {
            this.dialogVisible2 = false
        },

        updateOpened() {
            if (!this.editor || this.editor == null || this.editor == undefined) {
                const editor = new E("#blogWangEdit");
                this.editor = editor; // 保存创建的实例
            }
            console.log("this.editor", this.editor)
            // console.log("this.curContent",this.curContent)
            this.editor.create()
            this.editor.txt.html(this.curContent)
            // console.log("this.editor.txt.html",this.editor.txt.html())
            // console.log("this.curContent",this.curContent)
        },

        fileUploadSuccess(res) {
            if (res.code == 0) {
                this.blogform.firstPicture = res.data
            }
        },

        load() {
            request.get("/blog", {
                params: {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    search: this.blogSearch
                }

            }).then(res => {
                this.tableData = res.data.records,
                    this.total = res.data.total
            })
        },

        blogEdit(index, row) {
            this.curContent = row.content
            this.blogform = JSON.parse(JSON.stringify(row))
            this.dialogVisible = true
        },

        blogDelete(index, id) {
            request.delete("/blog/delete", {
                params: {
                    id
                }
            }).then(res => {
                this.load()
            })

        },

        handleSizeChange(pageSize) {
            this.pageSize = pageSize
            this.load()
        },

        handleCurrentChange(pageNum) {
            this.currentPage = pageNum
            this.load()
        },

        blogadd() {
            this.dialogVisible = true
            this.blogform = {}
        },

        blogsave() {
            this.blogform.content = this.editor.txt.html()
            if (this.blogform.id) {  // 更新
                request.put("/blog/update", this.blogform).then(res => {
                    console.log(res)

                    this.dialogVisible = false  // 关闭弹窗
                    this.load() // 刷新表格的数据
                })
            } else {  // 新增
                request.post("/blog/save", this.blogform).then(res => {
                    console.log(res)
                    this.dialogVisible = false  // 关闭弹窗
                    this.load() // 刷新表格的数据
                })
            }
        },


    }

}
</script>

<style lang="less" scoped>
@import "../../style/admin/table.less";
@import "../../style/admin/blog.less";
</style>
